package com.filter;

import com.bean.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebFilter(urlPatterns = {"/userList.jsp"})
public class UserFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpServletRequest req = (HttpServletRequest) request;
        ServletContext servletContext = request.getServletContext();
        List<User> onlineUsers = (List<User>) servletContext.getAttribute("onlineUsers");
        User user = (User) req.getSession().getAttribute("user");
        if (user != null && onlineUsers != null) {
            boolean contains = onlineUsers.contains(user);
            if (contains) {
                chain.doFilter(request, response);
                return;
            }
        }
        resp.sendRedirect("./login.jsp");
    }

    @Override
    public void destroy() {

    }
}
